<?php
/**
 * 发送消息，消息可能是群消息或者私聊(好友)消息
 * 这里的逻辑已经写好是通用的业务逻辑，一般来说开发者不用关心
 * 格式参见 http://www.layui.com/doc/modules/layim.html#on 里的sendMessage事件
 */
use Lib\Db;
require_once __DIR__ . '/__init.php';
_session_start();
$db = Db::instance('laychat');
//=======================================
$cook=$_GET['PHPSESSID'];

//区分前后台
//前--台
if(empty($_GET['uid'])){
    $cook = str_replace('.','-', $cook);
    $res_laychat=false;
    $res = $db->query("select * from `users` where id =$cook");
    if(!$res){
        $cook = str_replace('.','-', $cook);
        $res_laychat = $db->query("select * from `user_laychat` where username ='$cook'");
    }
    if($res_laychat){
        $se['laychat'] = array(
            'id'       => $cook,
            'username' => $cook,
            'sign'     => '',
            'avatar'   => config_img(1),
        );
    }else{
        $se['laychat'] = array(
            'id'       => "user-".$res[0]['id'],
            'username' => $res[0]['username'],
            'sign'     => $res[0]['sign'],
            'avatar'   => $res[0]['avatar'],
        );
    }

}else{
    //后--台
    $res_admin = $db->query("select * from `admins` where id ={$cook}");

    //昵称
    if(isset($res_admin[0]['name'])){
        $name = $res_admin[0]['name'];
    }else{
        $name = $res_admin[0]['username'];
    }


    $se['laychat'] = array(
        'id'       => "admin-".$cook,
        'username' => $name,
        'sign'     => '客服',
        'avatar'   => config_img(2),
    );
}



if (!isset($se['laychat'])) {
    exit_json(array(
        'code' => 400,
        'msg'  => '请登录'
    ));
}

// 聊天数据
$data = $_POST['data'];
//print_r($data);exit;
// 发送者，也就是当前登录用户的id
$from = $se['laychat']['id'];
// 发送给谁
$to   = $data['to']['id'];
// 类型，私聊(friend)还是群组(group)
$type = $data['to']['type'];

$ClientId_arr = Gateway::getClientIdByUid($to);
$arr_empty=array();
foreach ($ClientId_arr as $k=>$v){
    if(Gateway::isOnline($v)){
        $arr_empty[]=$v;
    }
}
if(empty($arr_empty)){
    exit_json(array('code'=>5002));
    //echo 2;exit;
}

// 消息格式
$message_data = array(
    'username' => $se['laychat']['username'],
    'avatar'   => $se['laychat']['avatar'],
    'id'       => $type === 'friend' ? $from : $to,
    'type'     => $type,
    'content'  => htmlspecialchars($data['mine']['content']),
    'myUrl'  => $data['mine']['myUrl'],
    'timestamp'=> time()*1000,
    'from_id'  => $from,
);

$chat_message = array(
    'message_type' => 'chatMessage',
    'data' => $message_data
);

// 根据类型走不同的接口发送
switch ($type) {
    // 私聊
    case 'friend':
        Gateway::sendToUid($to, json_encode($chat_message));
        break;
    // 群聊
    case 'group':
        Gateway::sendToGroup($to, json_encode($chat_message), $se['laychat']['client_id']);
        break;
}


$data_json = array(
    'from'      => $from,
    'to'        => $to,
    'data'      => json_encode($message_data),
    'timestamp' => time(),
    'type'      => $type,
);
//----------------------!--------------------------
//// 把PHP数组转成JSON字符串
$json_string = json_encode($data_json).'***';

$reseller_id=isset($res[0]['reseller_id']) ? $res[0]['reseller_id'] : $cook;

if($reseller_id){
//    $dir=$res[0]['reseller_id'];
//添加来自 客服的判断 记录客服日志
    if(!empty($_GET['uid'])){
        $dir=$_POST['data']['to']['id'];
        $cook=end(explode('-',$dir));
        $_admin_ = $db->query("select * from `users` where id ={$cook}");
        if(isset($_admin_[0]['reseller_id'])){
            $dir = $_admin_[0]['reseller_id'];
        }
        //    data[to][from_id]
    }else{
        $dir=$reseller_id;
    }

    if (!$dir) return false;
    $path=__DIR__.'/files/'.$dir;
    $filename = __DIR__.'/files/'.$dir.'/'.$cook.'.jsonp';
    if(!file_exists($path)) {
        mkdir(iconv("UTF-8", "GBK", $path),0777,true);
        //mkdir($dir,$mode,true);
        // 写入文件
        $res_file = file_put_contents($filename, $json_string,FILE_APPEND);
    }else{
        // 写入文件
        $res_file = file_put_contents($filename, $json_string,FILE_APPEND);
    }

}else{
    $dir='var';
    $filename=__DIR__.'/files/'.$dir.'/'.$cook.'.jsonp';
    if(file_exists($filename)){
        file_put_contents($filename, $json_string, FILE_APPEND);
    }else{
        // 写入文件
        file_put_contents($filename, $json_string,FILE_APPEND);
    }

}

$last_insert_id=1;
// 返回json
$code = $last_insert_id ? 0 : 500;
exit_json(array('code'=>$code));


